package com.v1.video.activity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.v1.video.R;
import com.v1.video.adapter.DragAdapter;
import com.v1.video.adapter.DragAdapter.OnUpdateListener;
import com.v1.video.adapter.OtherAdapter;
import com.v1.video.domain.Channel;
import com.v1.video.domain.CustomChannelLst;
import com.v1.video.util.Utility;
import com.v1.video.util.Utils;
import com.v1.video.view.CustomGridView;
import com.v1.video.view.DragGrid;
/**
 * 频道管理
 * @author wangfang
 *
 */
public class ChannelManagerActivity extends BaseActivity implements
		OnClickListener {

	private DragGrid mDragGrid;
	private CustomGridView mOtherGridView;
	private List<Channel> mChannelLst;
	private List<Channel> mOtherChannelLst;
	private DragAdapter mDragAdapter;
	private OtherAdapter mOtherAdapter;
	private boolean isMove = false;
	private TextView mTvSort,mTvChannelTip;
	private Handler mHandler = new Handler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_channelmanager);

	}

	@Override
	protected void initView() {
		// TODO Auto-generated method stub
		mTvSort = (TextView) this.findViewById(R.id.tv_sort);
		mDragGrid = (DragGrid) this.findViewById(R.id.userGridView);
		mOtherGridView = (CustomGridView) this.findViewById(R.id.otherGridView);
		mTvChannelTip = (TextView) this.findViewById(R.id.tv_channel_tip);
	}

	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		Intent intent = getIntent();
		int index = intent.getIntExtra("Index", 0);
		loadCachedData();
		mDragAdapter = new DragAdapter(this, mChannelLst);
		mDragAdapter.setIndex(index);
		mDragAdapter.setOnUpdateListener(new OnUpdateListener() {

			@Override
			public void onUpdateListener() {
				// TODO Auto-generated method stub
				setUiEditState(true);
			}
		});
		mDragGrid.setAdapter(mDragAdapter);
		mOtherAdapter = new OtherAdapter(this, mOtherChannelLst);
		mOtherGridView.setAdapter(mOtherAdapter);
	}

	@Override
	protected void setListener() {
		// TODO Auto-generated method stub
		this.findViewById(R.id.iv_close).setOnClickListener(this);
		mTvSort.setOnClickListener(this);
		mDragGrid.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					final int position, long id) {
				// TODO Auto-generated method stub
				if (isMove == true) {
					return;
				}
				isMove = true;
				if (position > 1 && mDragAdapter != null
						&& mDragAdapter.isEdit()) {
					mDragAdapter.setSort(true);
					final ImageView moveImageView = getView(view);
					if (moveImageView != null) {
						TextView newTextView = (TextView) view
								.findViewById(R.id.tv_item);
						final int[] startLocation = new int[2];
						newTextView.getLocationInWindow(startLocation);
						final Channel channel = ((DragAdapter) parent
								.getAdapter()).getItem(position);// 获取点击的频道内容
						mOtherAdapter.setVisible(false);
						// 添加到最后一个
						mOtherAdapter.addItem(0,channel);
						mHandler.postDelayed(new Runnable() {
							public void run() {
								try {
									int[] endLocation = new int[2];
									// 获取终点的坐标
									mOtherGridView.getChildAt(
											mOtherGridView
													.getFirstVisiblePosition())
											.getLocationInWindow(endLocation);
									MoveAnim(moveImageView, startLocation,
											endLocation, channel, mDragGrid);
									mDragAdapter.setRemove(position);
								} catch (Exception localException) {
								}
							}
						}, 50L);
					}
				} else if (mDragAdapter != null
						&& mDragAdapter.isEdit() == false) {
					isMove = false;
					Intent intent = new Intent();
					intent.putExtra("userChannel", (Serializable) mChannelLst);
					intent.putExtra("Index", position);
					intent.putExtra("isSort", mDragAdapter.isSort());
					setResult(RESULT_OK, intent);
					finish();
				}
			}
		});
		mOtherGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					final int position, long id) {
				// TODO Auto-generated method stub
				if (isMove == true) {
					return;
				}
				isMove = true;
				final ImageView moveImageView = getView(view);
				if (moveImageView != null) {
					mDragAdapter.setSort(true);
					TextView newTextView = (TextView) view
							.findViewById(R.id.tv_item);
					final int[] startLocation = new int[2];
					newTextView.getLocationInWindow(startLocation);
					final Channel channel = ((OtherAdapter) parent.getAdapter())
							.getItem(position);
					mDragAdapter.setVisible(false);
					// 添加到最后一个
					mDragAdapter.addItem(channel);
					mHandler.postDelayed(new Runnable() {
						public void run() {
							try {
								int[] endLocation = new int[2];
								// 获取终点的坐标
								mDragGrid.getChildAt(
										mDragGrid.getLastVisiblePosition())
										.getLocationInWindow(endLocation);
								MoveAnim(moveImageView, startLocation,
										endLocation, channel, mOtherGridView);
								mOtherAdapter.setRemove(position);
							} catch (Exception localException) {
							}
						}
					}, 50L);
				} else {
					isMove = false;
				}
			}
		});
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.iv_close:
			if (mDragAdapter.isSort()) {
				saveCachedData();
			}
			Intent intent = new Intent();
			intent.putExtra("userChannel", (Serializable) mDragAdapter.getChannnelLst());
			if (mDragAdapter != null) {
				intent.putExtra("Index", mDragAdapter.getIndex());
				intent.putExtra("isSort", mDragAdapter.isSort());
			}
			setResult(RESULT_OK, intent);
			this.finish();
			break;
		case R.id.tv_sort:
			String text = mTvSort.getText().toString();
			if (!TextUtils.isEmpty(text)) {
				if (text.equals(getResources().getString(R.string.channel_sort_text))) {
					setUiEditState(true);
				} else {
					setUiEditState(false);
					saveCachedData();
				}
			}
			break;
		default:
			break;
		}
	}
	
	private void loadCachedData(){
		String json = Utility.ReadTxtFile(this,
				"CustomChannelCache.txt");
		if (!TextUtils.isEmpty(json)) {
			Gson gson = new Gson();
			CustomChannelLst mCustomChannelLst = gson.fromJson(json,CustomChannelLst.class);
			mChannelLst = mCustomChannelLst.getUserLst();
			if (mCustomChannelLst.getOtherLst() == null) {
				mOtherChannelLst = new ArrayList<Channel>();
			} else {
				mOtherChannelLst = mCustomChannelLst.getOtherLst();
			}
		}
	}
	
	private void saveCachedData(){
		CustomChannelLst mChannelLst = new CustomChannelLst();
		mChannelLst.setUserLst(mDragAdapter.getChannnelLst());
		mChannelLst.setOtherLst(mOtherAdapter.getChannnelLst());
		Gson gson = new Gson();
		String jsonStr = gson.toJson(mChannelLst);
		Utility.CacheData(this, "CustomChannelCache.txt", jsonStr);
	}

	private void setUiEditState(boolean isEdit) {
		if (isEdit == true) {
			mTvSort.setText(getResources().getString(R.string.channel_complete_text));
			mTvChannelTip.setVisibility(View.VISIBLE);
			Utils.saveChannelOperate(this, true);
		} else {
			mTvSort.setText(getResources().getString(R.string.channel_sort_text));
			mTvChannelTip.setVisibility(View.GONE);
		}
		if (mDragAdapter != null) {
			mDragAdapter.setEdit(isEdit);
		}
	}

	/**
	 * 点击ITEM移动动画
	 * 
	 * @param moveView
	 * @param startLocation
	 * @param endLocation
	 * @param moveChannel
	 * @param clickGridView
	 */
	private void MoveAnim(View moveView, int[] startLocation,
			int[] endLocation, final Channel moveChannel,
			final GridView clickGridView) {
		int[] initLocation = new int[2];
		// 获取传递过来的VIEW的坐标
		moveView.getLocationInWindow(initLocation);
		// 得到要移动的VIEW,并放入对应的容器中
		final ViewGroup moveViewGroup = getMoveViewGroup();
		final View mMoveView = getMoveView(moveViewGroup, moveView,
				initLocation);
		// 创建移动动画
		TranslateAnimation moveAnimation = new TranslateAnimation(
				startLocation[0], endLocation[0], startLocation[1],
				endLocation[1]);
		moveAnimation.setDuration(300L);// 动画时间
		// 动画配置
		AnimationSet moveAnimationSet = new AnimationSet(true);
		moveAnimationSet.setFillAfter(false);// 动画效果执行完毕后，View对象不保留在终止的位置
		moveAnimationSet.addAnimation(moveAnimation);
		mMoveView.startAnimation(moveAnimationSet);
		moveAnimationSet.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
				isMove = true;
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationEnd(Animation animation) {
				moveViewGroup.removeView(mMoveView);
				// instanceof 方法判断2边实例是不是一样，判断点击的是DragGrid还是OtherGridView
				if (clickGridView instanceof DragGrid) {
					mOtherAdapter.setVisible(true);
					mOtherAdapter.notifyDataSetChanged();
					mDragAdapter.remove();
				} else {
					mDragAdapter.setVisible(true);
					mDragAdapter.notifyDataSetChanged();
					mOtherAdapter.remove();
				}
				isMove = false;
			}
		});
	}
	

	/**
	 * 获取移动的VIEW，放入对应ViewGroup布局容器
	 * 
	 * @param viewGroup
	 * @param view
	 * @param initLocation
	 * @return
	 */
	private View getMoveView(ViewGroup viewGroup, View view, int[] initLocation) {
		int x = initLocation[0];
		int y = initLocation[1];
		viewGroup.addView(view);
		LinearLayout.LayoutParams mLayoutParams = new LinearLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		mLayoutParams.leftMargin = x;
		mLayoutParams.topMargin = y;
		view.setLayoutParams(mLayoutParams);
		return view;
	}

	/**
	 * 创建移动的ITEM对应的ViewGroup布局容器
	 */
	private ViewGroup getMoveViewGroup() {
		ViewGroup moveViewGroup = (ViewGroup) getWindow().getDecorView();
		LinearLayout moveLinearLayout = new LinearLayout(this);
		moveLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		moveViewGroup.addView(moveLinearLayout);
		return moveLinearLayout;
	}

	/**
	 * 获取点击的Item的对应View，
	 * 
	 * @param view
	 * @return
	 */
	private ImageView getView(View view) {
		view.destroyDrawingCache();
		view.setDrawingCacheEnabled(true);
		Bitmap cache = Bitmap.createBitmap(view.getDrawingCache());
		view.setDrawingCacheEnabled(false);
		ImageView iv = new ImageView(this);
		iv.setImageBitmap(cache);
		return iv;
	}

}
